from flask import Flask, render_template, request, redirect, url_for, flash
import os
from flask_sqlalchemy import SQLAlchemy
import mysql.connector


app = Flask(__name__)

# 模拟的用户数据
users = {
    'teacher': [],
    'student': [],
    'parent': []
}


@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        if 'login' in request.form:
            user_type = request.form['user_type']
            username = request.form['username']
            password = request.form['password']

            for user in users[user_type]:
                if user['username'] == username and user['password'] == password:
                    return redirect(url_for(f'{user_type}_dashboard'))
            return render_template('login_failed.html')
        elif 'register' in request.form:
            return redirect(url_for('register'))
        elif 'forgot_password' in request.form:
            return redirect(url_for('forgot_password'))

    return render_template('login.html')


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        password = request.form['password']

        for user_type_key in users:
            for user in users[user_type_key]:
                if user['username'] == username:
                    return "用户名已存在，请选择其他用户名。"

        users[user_type].append({'username': username, 'password': password})
        return redirect(url_for('register_success'))

    return render_template('register.html')


@app.route('/register_success')
def register_success():
    return render_template('register_success.html')


@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        username = request.form['username']
        new_password = request.form['new_password']

        for user_type in users:
            for user in users[user_type]:
                if user['username'] == username:
                    user['password'] = new_password
                    return redirect(url_for('password_reset_success'))

        return "用户名不存在。"

    return render_template('forgot_password.html')


@app.route('/password_reset_success')
def password_reset_success():
    return render_template('password_reset_success.html')


@app.route('/student_dashboard')
def student_dashboard():
    return render_template('student_dashboard.html')


@app.route('/teacher_dashboard')
def teacher_dashboard():
    return render_template('teacher_dashboard.html')


@app.route('/parent_dashboard')
def parent_dashboard():
    return render_template('parent_dashboard.html')


app.config['UPLOAD_FOLDER'] = 'uploads/'
app.secret_key = 'your_secret_key'


@app.route('/create_exam', methods=['GET', 'POST'])
def create_exam():
    if request.method == 'POST':
     pass

    return render_template('create_exam.html')

def get_db_connection():
    conn = mysql.connector.connect(
        host='localhost',
        user='root',
        password='202466',
        database='question'
    )
    return conn


@app.route('/questions')
def question_list():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    cursor.execute('SELECT * FROM questions')
    questions = cursor.fetchall()

    # 调试输出，查看 questions 内容
    print(f"Questions retrieved: {questions}")

    cursor.close()
    conn.close()

    return render_template('question_list.html', questions=questions)


@app.route('/questions/edit/<int:question_id>', methods=['GET', 'POST'])
def edit_question(question_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    # 查询指定ID的题目
    cursor.execute('SELECT * FROM questions WHERE id = %s', (question_id,))
    question = cursor.fetchone()

    if request.method == 'POST':
        # 获取表单数据并更新题目
        sql = '''
        UPDATE questions
        SET text = %s, option_a = %s, option_b = %s, option_c = %s, option_d = %s, correct_answer = %s, question_type = %s
        WHERE id = %s
        '''
        cursor.execute(sql, (
            request.form['text'],
            request.form['option_a'],
            request.form['option_b'],
            request.form['option_c'],
            request.form['option_d'],
            request.form['correct_answer'],
            request.form['question_type'],
            question_id
        ))
        conn.commit()

        cursor.close()
        conn.close()

        return redirect(url_for('question_list'))

    cursor.close()
    conn.close()

    return render_template('edit_question.html', question=question)





if __name__ == '__main__':
    app.run(debug=True)

